package com.yx.changdao.web.controller;

import com.yx.changdao.common.data.RespCodeEnum;
import com.yx.changdao.common.data.Result;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: <br />
 * 异常捕获处理
 * <p>
 * <br />
 * @Auther: Zhangjiashun
 * @create 2019/11/12 9:49
 */
@Controller
public class StatusCodeExceptionHandler implements ErrorController {


    /**
     * 指定跳转路径/error
     */
    @Override
    public String getErrorPath() {
        return "/error";
    }


    /**
     * 400 请求无效
     */
    public Result error400() {
        return Result.error(RespCodeEnum.BAD_REQUEST, "请求无效");
    }


    /**
     * 用户认证失败
     */
    public Result error401() {
        return Result.error(RespCodeEnum.UNAUTHORIZED, "用户认证失败");
    }


    /**
     * 403 禁止访问
     */
    public Result error403() {
        return Result.error(RespCodeEnum.FORBIDDEN, "禁止访问");
    }


    /**
     * 404 请求的网页不存在
     */
    public Result error404() {
        return Result.error(RespCodeEnum.NOT_FOUND, "请求的网页不存在");
    }

    /**
     * 405 资源被禁止
     */
    public Result error405() {
        return Result.error(RespCodeEnum.METHOD_NOT_ALLOWED, "资源被禁止");
    }

    /**
     * 500 内部服务器错误,请联系管理员
     */
    public Result error500() {
        return Result.error(RespCodeEnum.INTERNAL_SERVER_ERROR, "内部服务器错误,请联系管理员");
    }


    /**
     * 处理错误状态码
     */
    @ResponseBody
    @RequestMapping("/error")
    public Result handleError(HttpServletRequest request) {
        // 状态码
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        // 错误原因
        Exception attribute = (Exception) request.getAttribute("javax.servlet.error.exception");
        if (statusCode == 400) {
            return error400();
        } else if (statusCode == 401) {
            return error401();
        } else if (statusCode == 403) {
            return error403();
        } else if (statusCode == 404) {
            return error404();
        } else if (statusCode == 405) {
            return error405();
        } else if (statusCode == 500) {
            //处理全局异常无法捕获过滤器中自定义异常问题
            String message = attribute.getCause().toString();
            if (message.startsWith(AuthenticationException.class.getName())) {
                return error401();
            } else {
                return error500();
            }
        } else {
            return error500();
        }
    }


}
